﻿
///// <reference path="../../jquery.js" />

/// <reference name="../../lib/jquery-1.3.1-vsdoc.js" />
///// <reference path="../jQueryFileTree.min.js" />
/// <reference path="../FileTree/jquery.fileTree.js" />


/*!
*   My explorer(Jquery Plugin)
*
* Copyright (c) 2009 Andy Huang
* Date: Monday, February 09, 2009
* Version: V1.0
*/
$(document).ready(function() {
    var explorer = { name: '', path: '', dir: true, selected: false, root: true };

    function addexpl(name, path, dir, selected, root) {
        explorer.name = name;
        explorer.path = path;
        explorer.dir = dir;
        explorer.selected = selected;
        explorer.root = root;

        //set current path
        $(".explorerState").text("Current Directory: "+path);
    }

    //left panel, file tree
    $("#fileTree").fileTree({ script: '../Services/CodeTree/GetFileTree.ashx' }, function (file) {
        $("#fileText").val(file.path); // set tree path
        //alert(file.path);
        if (!file.isLeaf) {
            var dir;
            if (file.collapse) {
                dir = file.path.substring(0, file.path.lastIndexOf('/'));
                dir = dir.substring(0, dir.lastIndexOf('/') + 1);
            }
            else {
                dir = file.path;
            }
            $("#fileGrid").fileGrid.reload(dir);
            console.log(dir);
            addexpl(file.name, file.path, !file.isLeaf, false, true);
        }
    });

    //right panel, file grid
    $("#fileGrid").fileGrid({ script: '../Services/CodeTree/GetFileGrid.ashx' }, function (file) {
        $("#fileText").val(file.path); // set tree path

        if (!file.isLeaf) {
            if (file.back)
                $("#fileTree").fileTree.reload(file.oPath, file.back);
            else
                $("#fileTree").fileTree.reload(file.path, file.back);

            addexpl(file.name, file.path, !file.isLeaf, false, true);
        }
        else {
            loadtext();
        }

    }, function(file) {
        if (file.focusPath) {
            $("#fileText").val(file.focusPath);
        }
    });
    //init
    fileTextboxButtonNotHide($("#fileText"), "#zoom");
    $(".explorerState").text("Current Directory: //");

    //hide sibling button
    function fileTextboxButtonNotHide(obj, val) {
        obj.siblings(":not(" + val + ")").hide();
        obj.siblings(val).show();
    }

    //file textbox
    $("#fileText").val("//").addClass("filetxt");

    //search, refresh
    $("#zoom,#refresh").click(function() {
        var obj = $("#fileText").val();
        if (obj) {
            $("#fileGrid").fileGrid.reload(obj);
            $("#fileTree").fileTree.reload(obj, false);
        }
    });

    //create new folder
    $("#new").click(function() {
        var para = { mode: 'sample', title: 'Create New Folder', firstboxval: $("#fileText").val() };
        //open dialog;
        $("#dialog").dialog(para, function(info) {
            opt("new", { dir: info.firstval });
        });

    });

    //create new file
    $("#newfile").click(function() {
        var para = { mode: 'two-new', title: 'Create New File', firstboxval: $("#fileText").val() };
        //open dialog;
        $("#dialog").dialog(para, function(info) {
            opt("newfile", { dir: info.firstval, text: info.multipleval });
        });
    });

    //delete
    $("#delete").click(function() {
        var obj = $("#fileGrid").find("div[currselect=true]");
        if (obj.length > 0) {
            var list = "";
            obj.each(function() {
                list += "," + $(this).children().attr("rel");
            });

            var para = { mode: 'sample', title: 'Delete', firstboxval: list.substring(1, list.length) };
            //open dialog;
            $("#dialog").dialog(para, function(info) {
                opt("delete", { dir: info.firstval });
            });
        }
        else {
            alert("Please Select File or Directory");
        }

    });

    //edit
    $("#edit").click(function() {
        var obj = $("#fileGrid").find("div[currselect=true]");
        if (obj.length != 1) {
            alert("Only/Need Select One File or Directory");
            return;
        }

        obj.each(function() {
            var d = $(this).children();
            var para = { mode: 'two-edit', title: 'Edit Folder', firstboxval: d.attr("rel"), secondboxval: d.attr("rel") };
            //open dialog;
            $("#dialog").dialog(para, function(info) {
                opt("edit", { dir: info.firstval, toDir: info.secondval });
            });
        });

    });

    //download
    $("#download").click(function() {
        fileTextboxButtonNotHide($("#fileText"), "#zoom");
        var obj = $("#fileGrid").find("div[currselect=true]");
        if (obj.length > 0) {
            obj.each(function() {
                var d = $(this).children();
                if (!d.hasClass("directory")) {
                    window.open("sr/Download.ashx?dir=" + d.attr("rel"));
                }
                else {
                    alert("Cannot Download Folder,Files Only.");
                }
            });
        }
        else {
            alert("Please Select File");
        }
    });

    //compress
    $("#compress").click(function() {
        var cpr = { files: [], directorys: [] };
        $("#fileGrid").find("div[currselect=true]").each(function() {
            var d = $(this).children();
            if (d.hasClass("directory")) {
                cpr.directorys.push(d.attr("rel"));
            }
            else {
                cpr.files.push(d.attr("rel"));
            }
        });

        if (cpr.files.length != 0 && cpr.directorys.length != 0) {
            var para = { mode: 'sample', title: 'Compress', firstboxval: cpr.files.join(",") + "," + cpr.directorys.join(",") };
            //open dialog;
            $("#dialog").dialog(para, function(info) {
                opt("compress", cpr);
            });
        }
        else {
            if (cpr.files.length != 0 && cpr.directorys.length == 0) {
                var para = { mode: 'sample', title: 'Compress', firstboxval: cpr.files.join(",") };
                //open dialog;
                $("#dialog").dialog(para, function(info) {
                    opt("compressfiles", { files: cpr.files });
                });

            } else if (cpr.files.length == 0 && cpr.directorys.length != 0) {
                var para = { mode: 'sample', title: 'Compress', firstboxval: cpr.directorys.join(",") };
                //open dialog;
                $("#dialog").dialog(para, function(info) {
                    opt("compressdirectorys", { directorys: cpr.directorys });
                });
            }
        }

    });
    //decompress
    $("#decompress").click(function() {
        var cpr = { files: [] };
        $("#fileGrid").find("div[currselect=true]").each(function() {
            var d = $(this).children();
            if (!d.hasClass("directory")) {
                cpr.files.push(d.attr("rel"));
            }
        });
        if (cpr.files.length != 0) {
            var para = { mode: 'sample', title: 'Decompress', firstboxval: cpr.files.join(",") };
            //open dialog;
            $("#dialog").dialog(para, function(info) {
                opt("decompress", cpr);
            });
        }
        else {
            alert("Please Select Gzip file");
        }
    });
    //upload
    $("#buttonUpload").click(function() {
        $("#loading")
		    .ajaxStart(function() {
		        $(this).show();
		    })
		    .ajaxComplete(function() {
		        $(this).hide();
		    });

        $.ajaxFileUpload({
            url: 'sr/Upload.ashx?path=' + explorer.path,
            secureuri: false,
            fileElementId: 'fileToUpload',
            success: function(data, status) {
                $("#fileGrid").fileGrid.reload(explorer.path);
                $("#fileTree").fileTree.reload(explorer.path, true);
            },
            error: function(data, status, e) {
                alert(e);
            }
        });
    });


    function opt(state, datas) {
        switch (state) {
            case "new":
                ajax("sr/FileOperation.asmx/CreateFolder", datas);
                break;
            case "newfile":
                ajax("sr/FileOperation.asmx/CreateFile", datas);
                break;
            case "delete":
                ajax("sr/FileOperation.asmx/Delete", datas);
                break;
            case "edit":
                ajax("sr/FileOperation.asmx/Edit", datas);
                break;
            case "compress":
                ajax("sr/FileOperation.asmx/Compress", datas);
                break;
            case "compressfiles":
                ajax("sr/FileOperation.asmx/CompressFiles", datas);
                break;
            case "compressdirectorys":
                ajax("sr/FileOperation.asmx/CompressDirectorys", datas);
                break;
            case "decompress":
                ajax("sr/FileOperation.asmx/Decompress", datas);
                break;
        }

    }

    function ajax(script, datas) {
        var option = {
            url: script,
            type: "POST",
            beforeSend: function(XMLHttpRequest) {
                fileTextboxButtonNotHide($("#fileText").blur(), "#loading");
            },
            complete: function(XMLHttpRequest, textStatus) {
                fileTextboxButtonNotHide($("#fileText").blur(), "#zoom");
            },
            data: datas,
            success: function(data, textStatus) {
                $(data).find("OperationState").each(function() {
                    if ($(this).text() == "OK") {
                        $("#dialog").dialog.close();
                        $("#fileGrid").fileGrid.reload(explorer.path);
                        $("#fileTree").fileTree.reload(explorer.path, true);
                    } else {
                        alert("Error!");
                    }
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
                $("#dialog").dialog.close();
            }
        };
        $.ajax(option);
    }
    //load text file
    function loadtext() {
        var text = "";
        var option = {
            url: "sr/FileOperation.asmx/LoadFileText",
            type: "POST",
            beforeSend: function(XMLHttpRequest) {
                fileTextboxButtonNotHide($("#fileText").blur(), "#loading");
            },
            complete: function(XMLHttpRequest, textStatus) {
                fileTextboxButtonNotHide($("#fileText").blur(), "#zoom");
            },
            data: { dir: $("#fileText").val() },
            success: function(data, textStatus) {
                $(data).find("string").each(function() {
                    text += $(this).text();
                });

                var para = { mode: 'two-new', title: 'Edit File', firstboxval: $("#fileText").val(), multipleboxval: text };
                //open dialog;
                $("#dialog").dialog(para, function(info) {
                    opt("newfile", { dir: info.firstval, text: info.multipleval });
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
                $("#dialog").dialog.close();
            }
        };
        $.ajax(option);
    }

});